from beanie import Document, Indexed
from pydantic import BaseModel, Field
from datetime import datetime
from typing import Optional, List, Any, Dict
from enum import Enum

class VisaStatus(str, Enum):
    """签证状态枚举"""
    PENDING = "pending"
    APPROVED = "approved"
    REJECTED = "rejected"
    IN_REVIEW = "in_review"
    INTERVIEW_SCHEDULED = "interview_scheduled"

class VisaType(str, Enum):
    """签证类型枚举"""
    TOURIST = "tourist"
    BUSINESS = "business"
    STUDENT = "student"
    WORK = "work"
    FAMILY = "family"
    TRANSIT = "transit"

class VisaApplication(Document):
    """签证申请记录"""
    
    # 基本信息
    applicant_name: str = Field(..., description="申请人姓名")
    passport_number: str = Field(..., description="护照号码")
    nationality: str = Field(..., description="国籍")
    
    # 签证信息
    visa_type: VisaType = Field(..., description="签证类型")
    destination_country: str = Field(..., description="目的地国家")
    embassy_location: str = Field(..., description="领事馆位置")
    
    # 状态信息
    status: VisaStatus = Field(default=VisaStatus.PENDING, description="签证状态")
    application_date: datetime = Field(default_factory=datetime.utcnow, description="申请日期")
    last_updated: datetime = Field(default_factory=datetime.utcnow, description="最后更新时间")
    
    # 处理信息
    processing_time_estimate: Optional[str] = Field(None, description="预计处理时间")
    actual_processing_time: Optional[int] = Field(None, description="实际处理时间（天数）")
    
    # 费用信息
    application_fee: Optional[float] = Field(None, description="申请费用")
    service_fee: Optional[float] = Field(None, description="服务费用")
    
    # 文档信息
    required_documents: List[str] = Field(default_factory=list, description="所需文档")
    submitted_documents: List[str] = Field(default_factory=list, description="已提交文档")
    
    # 面试信息
    interview_required: bool = Field(default=False, description="是否需要面试")
    interview_date: Optional[datetime] = Field(None, description="面试日期")
    interview_location: Optional[str] = Field(None, description="面试地点")
    
    # 结果信息
    decision_date: Optional[datetime] = Field(None, description="决定日期")
    visa_valid_from: Optional[datetime] = Field(None, description="签证有效期开始")
    visa_valid_until: Optional[datetime] = Field(None, description="签证有效期结束")
    
    # 备注和额外信息
    notes: Optional[str] = Field(None, description="备注")
    additional_info: Dict[str, Any] = Field(default_factory=dict, description="额外信息")
    
    class Settings:
        name = "visa_applications"
        indexes = [
            [("passport_number", 1)],
            [("status", 1)],
            [("destination_country", 1)],
            [("application_date", -1)],
        ]

class DiscoursePost(Document):
    """Discourse 帖子记录"""
    
    post_id: int = Field(..., description="帖子 ID")
    topic_id: int = Field(..., description="主题 ID")
    category_id: Optional[int] = Field(None, description="分类 ID")
    
    title: str = Field(..., description="帖子标题")
    content: str = Field(..., description="帖子内容")
    author: str = Field(..., description="作者")
    
    created_at: datetime = Field(..., description="创建时间")
    updated_at: Optional[datetime] = Field(None, description="更新时间")
    
    # 统计信息
    reply_count: int = Field(default=0, description="回复数")
    like_count: int = Field(default=0, description="点赞数")
    view_count: int = Field(default=0, description="查看数")
    
    # 相关签证信息
    related_countries: List[str] = Field(default_factory=list, description="相关国家")
    visa_types: List[str] = Field(default_factory=list, description="签证类型")
    
    # 提取的关键信息
    processing_time_mentioned: Optional[str] = Field(None, description="提到的处理时间")
    success_rate: Optional[float] = Field(None, description="成功率")
    
    tags: List[str] = Field(default_factory=list, description="标签")
    
    class Settings:
        name = "discourse_posts"
        indexes = [
            [("post_id", 1)],
            [("topic_id", 1)],
            [("created_at", -1)],
            [("related_countries", 1)],
        ]

class ScrapedWebsite(Document):
    """爬取的网站数据"""
    
    url: str = Field(..., description="网站 URL")
    title: Optional[str] = Field(None, description="页面标题")
    content: str = Field(..., description="页面内容")
    
    scraped_at: datetime = Field(default_factory=datetime.utcnow, description="爬取时间")
    last_updated: datetime = Field(default_factory=datetime.utcnow, description="最后更新时间")
    
    # 网站类型
    site_type: str = Field(..., description="网站类型 (embassy, visa_service, forum, etc.)")
    country: Optional[str] = Field(None, description="相关国家")
    
    # 提取的信息
    visa_requirements: List[str] = Field(default_factory=list, description="签证要求")
    processing_times: List[str] = Field(default_factory=list, description="处理时间")
    fees: List[str] = Field(default_factory=list, description="费用信息")
    appointment_info: Optional[str] = Field(None, description="预约信息")
    
    # 链接和图片
    links: List[str] = Field(default_factory=list, description="页面链接")
    images: List[str] = Field(default_factory=list, description="图片链接")
    
    # 元数据
    http_status: int = Field(..., description="HTTP 状态码")
    content_hash: Optional[str] = Field(None, description="内容哈希值")
    
    class Settings:
        name = "scraped_websites"
        indexes = [
            [("url", 1)],
            [("scraped_at", -1)],
            [("country", 1)],
            [("site_type", 1)],
        ]

class VisaStatistics(Document):
    """签证统计数据"""
    
    country: str = Field(..., description="国家")
    visa_type: VisaType = Field(..., description="签证类型")
    embassy_location: str = Field(..., description="领事馆位置")
    
    # 统计时间范围
    period_start: datetime = Field(..., description="统计开始时间")
    period_end: datetime = Field(..., description="统计结束时间")
    
    # 申请统计
    total_applications: int = Field(default=0, description="总申请数")
    approved_applications: int = Field(default=0, description="批准申请数")
    rejected_applications: int = Field(default=0, description="拒绝申请数")
    pending_applications: int = Field(default=0, description="待处理申请数")
    
    # 处理时间统计
    avg_processing_time: Optional[float] = Field(None, description="平均处理时间（天）")
    min_processing_time: Optional[int] = Field(None, description="最短处理时间（天）")
    max_processing_time: Optional[int] = Field(None, description="最长处理时间（天）")
    
    # 成功率
    approval_rate: float = Field(default=0.0, description="批准率")
    
    # 费用统计
    avg_total_cost: Optional[float] = Field(None, description="平均总费用")
    
    created_at: datetime = Field(default_factory=datetime.utcnow)
    updated_at: datetime = Field(default_factory=datetime.utcnow)
    
    class Settings:
        name = "visa_statistics"
        indexes = [
            [("country", 1), ("visa_type", 1)],
            [("period_start", 1), ("period_end", 1)],
            [("created_at", -1)],
        ]

# 用于 API 响应的 Pydantic 模型
class VisaApplicationResponse(BaseModel):
    """签证申请响应模型"""
    id: str
    applicant_name: str
    visa_type: VisaType
    destination_country: str
    status: VisaStatus
    application_date: datetime
    last_updated: datetime

class VisaApplicationCreate(BaseModel):
    """创建签证申请的请求模型"""
    applicant_name: str
    passport_number: str
    nationality: str
    visa_type: VisaType
    destination_country: str
    embassy_location: str
    interview_required: bool = False
    notes: Optional[str] = None

class VisaApplicationUpdate(BaseModel):
    """更新签证申请的请求模型"""
    status: Optional[VisaStatus] = None
    processing_time_estimate: Optional[str] = None
    interview_date: Optional[datetime] = None
    interview_location: Optional[str] = None
    decision_date: Optional[datetime] = None
    visa_valid_from: Optional[datetime] = None
    visa_valid_until: Optional[datetime] = None
    notes: Optional[str] = None
